<template>
  <ContentWrap>
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="page-title">
          <Icon icon="ep:user" class="title-icon" />
          <div class="title-text">
            <h2>广告账户</h2>
            <p>管理广告平台账户和授权信息</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索工作栏 -->
    <div class="search-container">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
        class="search-form"
      >
        <div class="search-row">
          <el-form-item label="渠道" prop="channelId" class="search-item">
            <el-select
              v-model="queryParams.channelId"
              placeholder="请选择渠道"
              :loading="remoteLoading"
              @change="handleQuery"
              class="search-select"
            >
              <el-option
                v-for="item in channelList"
                :key="item.id"
                :label="item.name"
                :value="item.id!"
              >
                <div class="option-item">
                  <Icon icon="ep:connection" class="option-icon" />
                  <span>{{ item.name }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="账户名称" prop="name" class="search-item">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入账户名称"
              clearable
              @keyup.enter="handleQuery"
              class="search-input"
            >
              <template #prefix>
                <Icon icon="ep:user" class="input-icon" />
              </template>
            </el-input>
          </el-form-item>
        </div>

        <div class="search-actions">
          <el-button class="search-btn" @click="handleQuery">
            <Icon icon="ep:search" class="btn-icon" />
            <span class="btn-text">搜索</span>
          </el-button>
          <el-button class="reset-btn" @click="resetQuery">
            <Icon icon="ep:refresh" class="btn-icon" />
            <span class="btn-text">重置</span>
          </el-button>
          <el-button
            type="primary"
            class="add-btn"
            @click="openForm('create')"
            v-hasPermi="['ad:account:create']"
          >
            <Icon icon="ep:plus" class="btn-icon" />
            <span class="btn-text">新增账户</span>
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 标签页和列表容器 -->
    <div class="table-container">
      <!-- 渠道标签页 -->
      <div class="tabs-container">
        <el-tabs v-model="activeName" @tab-click="handleTabClick" class="channel-tabs">
          <el-tab-pane :label="tab.name" :name="tab.id" v-for="tab in channelList" :key="tab.id">
            <template #label>
              <div class="tab-label">
                <Icon icon="ep:connection" class="tab-icon" />
                <span>{{ tab.name }}</span>
              </div>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        class="account-table"
      >
        <el-table-column label="账户名称" align="center" prop="name" min-width="150">
          <template #default="scope">
            <div class="name-cell">
              <Icon icon="ep:user" class="name-icon" />
              <span class="name-text">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="广告账户/商户ID" align="center" prop="accountId" min-width="150">
          <template #default="scope">
            <div class="account-id-cell">
              <Icon icon="ep:key" class="account-id-icon" />
              <span class="account-id-text">{{ scope.row.accountId }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="授权方式" align="center" min-width="150">
          <template #default="scope">
            <el-tag :type="scope.row.authType == 1 ? 'primary' : 'success'" class="auth-type-tag">
              <Icon
                :icon="scope.row.authType == 1 ? 'ep:platform' : 'ep:user-filled'"
                class="tag-icon"
              />
              {{ scope.row.authType == 1 ? '自有开放平台授权' : 'CRM代理授权' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="APIKEY" align="center" prop="apiKey" min-width="150">
          <template #default="scope">
            <div class="api-cell">
              <Icon icon="ep:key" class="api-icon" />
              <span class="api-text">{{ scope.row.apiKey }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="API密钥" align="center" prop="apiSecret" min-width="150">
          <template #default="scope">
            <div class="secret-cell">
              <Icon icon="ep:hide" class="secret-icon" />
              <span class="secret-text">{{ maskSecret(scope.row.apiSecret) }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="授权状态" align="center" prop="authStatus" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.authStatus == 1 ? 'success' : 'warning'" class="status-tag">
              <Icon
                :icon="scope.row.authStatus == 1 ? 'ep:check' : 'ep:warning'"
                class="tag-icon"
              />
              {{ scope.row.authStatus == 1 ? '已授权' : '未授权' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="已授权账号" align="center" width="120">
          <template #default="scope">
            <el-button
              link
              type="primary"
              class="view-btn"
              @click="showAdvertiserList(scope.row.id)"
            >
              <Icon icon="ep:view" class="btn-icon" />
              查看账号
            </el-button>
          </template>
        </el-table-column>

        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180"
        >
          <template #default="scope">
            <div class="time-cell">
              <Icon icon="ep:clock" class="time-icon" />
              <span class="time-text">{{
                dateFormatter(scope.row, scope.column, scope.row.createTime)
              }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="340" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                link
                type="primary"
                class="action-btn auth-btn"
                @click="getAuthUrl(scope.row.id)"
                v-hasPermi="['ad:account:update']"
              >
                <Icon icon="ep:link" class="action-icon" />
                <span class="action-text">获取授权链接</span>
              </el-button>
              <el-button
                link
                type="primary"
                class="action-btn edit-btn"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['ad:account:update']"
              >
                <Icon icon="ep:edit" class="action-icon" />
                <span class="action-text">编辑</span>
              </el-button>
              <el-button
                link
                type="danger"
                class="action-btn delete-btn"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['ad:account:delete']"
              >
                <Icon icon="ep:delete" class="action-icon" />
                <span class="action-text">删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
          class="custom-pagination"
        />
      </div>
    </div>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AccountForm ref="formRef" @success="getList" />
  <AdvertiserList ref="advertiserListRef" @success="getList" />
</template>

<script setup lang="ts">
import * as AccountApi from '@/api/ad/account'
import { getChannelSimpleList } from '@/api/ad/channel'
import AccountForm from './AccountForm.vue'
import AdvertiserList from './AdvertiserList.vue'
import { dateFormatter } from '@/utils/formatTime'

defineOptions({ name: 'AdAccount' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const activeName = ref()

const channelList = ref([])
const getChannelSimpleListFn = async () => {
  const data = await getChannelSimpleList()
  channelList.value = data
  activeName.value = channelList.value[0].id
  queryParams.channelId = channelList.value[0].id
}
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  channelId: null,
  name: null,
  accountId: null,
  apiKey: null,
  apiSecret: null,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 隐藏敏感信息
const maskSecret = (secret: string) => {
  if (!secret || secret.length <= 8) return secret
  return secret.substring(0, 4) + '****' + secret.substring(secret.length - 4)
}

/** 添加/修改操作 */
const advertiserListRef = ref()
// 查看已授权账号列表
const showAdvertiserList = (id) => {
  advertiserListRef.value.open(id)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AccountApi.getAccountPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** tab 切换 */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.channelId = tab.paneName
  handleQuery()
}

// 获取授权链接
const getAuthUrl = async (id) => {
  const data = await AccountApi.getAuthUrl(id)
  if (data) {
    window.open(data)
  } else {
    message.error('无法获取授权链接')
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, channelList.value, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AccountApi.deleteAccount(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(async () => {
  await getChannelSimpleListFn()
  await getList()
})
</script>

<style lang="scss" scoped>
// 页面头部
.page-header {
  margin-bottom: 24px;
  padding: 12px 24px;
  background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
  border-radius: 16px;
  color: white;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title-icon {
  font-size: 32px;
  color: rgba(255, 255, 255, 0.9);
}

.title-text {
  h2 {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 4px 0;
    color: white;
  }

  p {
    font-size: 14px;
    margin: 0;
    color: rgba(255, 255, 255, 0.8);
  }
}

// 搜索容器
.search-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
}

.search-form {
  .search-row {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 20px;
  }

  .search-item {
    flex: 1;
    min-width: 260px;
    margin-bottom: 0;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #374151;
    }
  }
}

.search-input {
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;

    &:hover {
      border-color: #d1d5db;
    }

    &.is-focus {
      border-color: #0052cc;
      box-shadow: 0 0 0 3px rgba(0, 82, 204, 0.1);
    }
  }

  .input-icon {
    color: #9ca3af;
    font-size: 16px;
  }
}

.search-select {
  width: 100%;

  :deep(.el-select__wrapper) {
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;

    &:hover {
      border-color: #d1d5db;
    }

    &.is-focused {
      border-color: #0052cc;
      box-shadow: 0 0 0 3px rgba(0, 82, 204, 0.1);
    }
  }
}

.option-item {
  display: flex;
  align-items: center;
  gap: 8px;

  .option-icon {
    font-size: 14px;
    color: #6b7280;
  }
}

.search-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.search-btn,
.reset-btn,
.add-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;

  .btn-icon {
    font-size: 16px;
  }

  &:hover {
    transform: translateY(-1px);
  }
}

.search-btn {
  background: #f3f4f6;
  border: 2px solid #e5e7eb;
  color: #374151;

  &:hover {
    background: #e5e7eb;
    border-color: #d1d5db;
  }
}

.reset-btn {
  background: #fef3c7;
  border: 2px solid #fbbf24;
  color: #92400e;

  &:hover {
    background: #fde68a;
    border-color: #f59e0b;
  }
}

.add-btn {
  background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
  border: none;
  color: white;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
  }
}

// 表格容器
.table-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
}

// 标签页样式
.tabs-container {
  padding: 20px 20px 0;
  border-bottom: 1px solid #f1f5f9;
}

.channel-tabs {
  :deep(.el-tabs__header) {
    margin: 0;

    .el-tabs__nav-wrap {
      &::after {
        display: none;
      }
    }

    .el-tabs__item {
      padding: 12px 20px;
      border-radius: 8px 8px 0 0;
      margin-right: 8px;
      transition: all 0.3s ease;

      &.is-active {
        background: #0052cc;
        color: white;
        border-bottom-color: #0052cc;
      }

      &:hover:not(.is-active) {
        background: rgba(0, 82, 204, 0.1);
        color: #0052cc;
      }
    }
  }
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 6px;

  .tab-icon {
    font-size: 14px;
  }
}

.account-table {
  :deep(.el-table__header) {
    background: #f8fafc;

    th {
      background: #f8fafc !important;
      color: #374151;
      font-weight: 600;
      border-bottom: 2px solid #e5e7eb;
      padding: 16px 12px;
    }
  }

  :deep(.el-table__body) {
    tr {
      transition: all 0.2s ease;

      &:hover {
        background: #f8fafc !important;
      }

      td {
        padding: 16px 12px;
        border-bottom: 1px solid #f1f5f9;
      }
    }
  }
}

// 表格单元格样式
.name-cell {
  display: flex;
  align-items: center;
  gap: 8px;

  .name-icon {
    color: #0052cc;
    font-size: 16px;
    flex-shrink: 0;
  }

  .name-text {
    font-weight: 500;
    color: #374151;
  }
}

.account-id-cell {
  display: flex;
  align-items: center;
  gap: 6px;

  .account-id-icon {
    color: #f59e0b;
    font-size: 14px;
  }

  .account-id-text {
    color: #6b7280;
    font-family: 'Courier New', monospace;
    font-size: 13px;
  }
}

.auth-type-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  border-radius: 6px;
  font-weight: 500;

  .tag-icon {
    font-size: 12px;
  }
}

.api-cell {
  display: flex;
  align-items: center;
  gap: 6px;

  .api-icon {
    color: #6366f1;
    font-size: 14px;
    flex-shrink: 0;
  }

  .api-text {
    color: #6b7280;
    font-family: 'Courier New', monospace;
    font-size: 12px;
  }
}

.secret-cell {
  display: flex;
  align-items: center;
  gap: 6px;

  .secret-icon {
    color: #ef4444;
    font-size: 14px;
    flex-shrink: 0;
  }

  .secret-text {
    color: #ef4444;
    font-family: 'Courier New', monospace;
    font-size: 12px;
    font-weight: 500;
  }
}

.status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  border-radius: 6px;
  font-weight: 500;

  .tag-icon {
    font-size: 12px;
  }
}

.view-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.2s ease;

  .btn-icon {
    font-size: 14px;
  }

  &:hover {
    background: rgba(0, 82, 204, 0.1);
    color: #0052cc;
  }
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 6px;

  .time-icon {
    color: #f59e0b;
    font-size: 14px;
  }

  .time-text {
    color: #6b7280;
    font-size: 13px;
  }
}

// 操作按钮
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.2s ease;

  .action-icon {
    font-size: 14px;
  }

  &.auth-btn {
    &:hover {
      background: rgba(16, 185, 129, 0.1);
      color: #10b981;
    }
  }

  &.edit-btn {
    &:hover {
      background: rgba(0, 82, 204, 0.1);
      color: #0052cc;
    }
  }

  &.delete-btn {
    &:hover {
      background: rgba(239, 68, 68, 0.1);
      color: #ef4444;
    }
  }
}

// 分页容器
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 24px;
  border-top: 1px solid #f1f5f9;
}

.custom-pagination {
  :deep(.el-pagination) {
    .el-pager li {
      border-radius: 6px;
      margin: 0 2px;

      &.is-active {
        background: #0052cc;
        color: white;
      }
    }

    .btn-prev,
    .btn-next {
      border-radius: 6px;
    }
  }
}

// H5 响应式设计
@media (max-width: 768px) {
  .page-header {
    padding: 12px 20px;
    margin-bottom: 16px;

    .title-text {
      h2 {
        font-size: 20px;
      }

      p {
        font-size: 13px;
      }
    }
  }

  .search-container {
    padding: 16px;

    .search-row {
      flex-direction: column;
      gap: 16px;

      .search-item {
        min-width: auto;
      }
    }

    .search-actions {
      justify-content: stretch;

      .search-btn,
      .reset-btn,
      .add-btn {
        flex: 1;
        justify-content: center;
      }
    }
  }

  .tabs-container {
    padding: 16px 16px 0;
  }

  .channel-tabs {
    :deep(.el-tabs__header) {
      .el-tabs__item {
        padding: 10px 16px;
        margin-right: 4px;
        font-size: 14px;
      }
    }
  }

  .table-container {
    overflow-x: auto;

    .account-table {
      min-width: 1200px;
    }
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;

    .action-btn {
      .action-text {
        display: none;
      }
    }
  }
}

@media (max-width: 480px) {
  .page-header {
    padding: 12px 16px;

    .page-title {
      gap: 12px;

      .title-icon {
        font-size: 24px;
      }

      .title-text {
        h2 {
          font-size: 18px;
        }
      }
    }
  }

  .search-container {
    padding: 12px;

    .search-actions {
      flex-direction: column;
      gap: 8px;
    }
  }

  .tabs-container {
    padding: 12px 12px 0;
  }

  .channel-tabs {
    :deep(.el-tabs__header) {
      .el-tabs__item {
        padding: 8px 12px;
        font-size: 13px;
      }
    }
  }

  .account-table {
    :deep(.el-table__header) {
      th {
        padding: 12px 8px;
        font-size: 13px;
      }
    }

    :deep(.el-table__body) {
      tr td {
        padding: 12px 8px;
      }
    }
  }

  .btn-text {
    display: none;
  }
}

// 深色模式支持
@media (prefers-color-scheme: dark) {
  .search-container,
  .table-container {
    background: #1e293b;
    border-color: #334155;
  }

  .tabs-container {
    border-color: #334155;
  }

  .channel-tabs {
    :deep(.el-tabs__header) {
      .el-tabs__item {
        &.is-active {
          background: #0052cc;
        }

        &:hover:not(.is-active) {
          background: rgba(0, 82, 204, 0.2);
        }
      }
    }
  }

  .account-table {
    :deep(.el-table__header) {
      th {
        background: #0f172a !important;
        color: #f1f5f9;
        border-color: #334155;
      }
    }

    :deep(.el-table__body) {
      tr {
        &:hover {
          background: #334155 !important;
        }

        td {
          border-color: #334155;
        }
      }
    }
  }

  .name-cell .name-text,
  .account-id-cell .account-id-text,
  .api-cell .api-text,
  .time-cell .time-text {
    color: #f1f5f9;
  }
}
</style>
